package com.myrice.remote;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

public final class RemoteTypeMapper {
	private static final Logger log = Logger.getLogger(RemoteTypeMapper.class);
	private static final Map<String, RemoteType> clazz2rt = new HashMap<String, RemoteType>();
	private static final Map<Byte, RemoteType> type2rt = new HashMap<Byte, RemoteType>();

	public static void regist(Class<?> clazz, RemoteType rt) {
		// if (clazz2rt.containsKey(clazz.getCanonicalName()))
		// throw new IllegalArgumentException("已被注册的本地类型：" + clazz);
		// if (type2rt.containsKey(rt.getType()))
		// throw new IllegalArgumentException("已被注册的远程类型：" + rt.getType());
		clazz2rt.put(clazz.getCanonicalName(), rt);
		type2rt.put(rt.getType(), rt);

		log.debug("regist type,  code: " + rt.getType() + "  class: "
				+ clazz.getCanonicalName() + "  convertor-class: "
				+ rt.getClass().getCanonicalName());
	}

	public static RemoteType mapping(Class<?> clazz) {
		String other = clazz.getCanonicalName();
		RemoteType rt = clazz2rt.get(other);
		if (rt == null) {
			rt = new RemoteType4Custom(clazz);
		}
		return rt;
	}

	public static RemoteType read(ObjectInput in) throws IOException {
		byte type = in.readByte();
		RemoteType rt = type2rt.get(type);
		if (rt == null)
			try {
				RemoteType4Custom ort = new RemoteType4Custom(in);
				if (!clazz2rt.containsKey(ort.getName())) {
					clazz2rt.put(ort.getName(), ort);
					rt = ort;
				} else {
					rt = clazz2rt.get(ort.getName());
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		return rt;
	}

	public static void write(RemoteType type, ObjectOutput out)
			throws IOException {
		out.writeByte(type.getType());
		type.writeExternal(out);
	}

	private RemoteTypeMapper() {
	}

}
